package com.biodiv.community.service.login.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.biodiv.community.converter.LoginConverter;
import com.biodiv.community.manager.cache.RedisCacheManager;
import com.biodiv.community.constant.RedisKeys;
import com.biodiv.community.entity.User;
import com.biodiv.community.enums.ErrorEnum;
import com.biodiv.community.exception.CommunityException;
import com.biodiv.community.mapper.UserMapper;
import com.biodiv.community.request.login.LoginDTO;
import com.biodiv.community.request.login.RegisterDTO;
import com.biodiv.community.response.login.LoginVO;
import com.biodiv.community.service.login.LoginService;
import com.biodiv.community.threadLocal.UserContext;
import com.biodiv.community.utils.JwtUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import static com.biodiv.community.constant.UserConstant.DEFAULT_AVATAR;

/**
 * @author: tianquan
 * @date: 2025-06-14  12:54
 * @description: TODO
 */
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {

    private final RedisCacheManager redisCacheManager;
    private final UserMapper userMapper;

    @Override
    public LoginVO login(LoginDTO loginDTO) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, loginDTO.getPhone());
        queryWrapper.eq(User::getPassword, loginDTO.getPassword());

        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new CommunityException(ErrorEnum.USER_NOT_FOUND);
        }

        Long userid = user.getId();

        String token = JwtUtils.generateToken(user.getId());
        redisCacheManager.set(RedisKeys.USER_TOKEN_PREFIX + userid, token);

        LoginVO loginVO = LoginConverter.INSTANCE.convert(user);
        loginVO.setUserId(userid);
        loginVO.setToken(token);

        return loginVO;
    }


    @Override
    public boolean register(RegisterDTO registerDTO) {

        User user= new User();
        user.setAvatar(DEFAULT_AVATAR);

        return false;
    }

    @Override
    public void logout() {
        // 清除redis中的缓存
        redisCacheManager.delete(RedisKeys.USER_TOKEN_PREFIX + UserContext.getUserId());
    }

}
